(defun pentagonal(n)
  (/ (* n (1- (* 3 n))) 2))

(defun all-pentagonals (max)
  (loop for i from 1 to max 
     with p = (make-array max :fill-pointer 0)
     do (vector-push (pentagonal i) p)
     finally (return p)))

(defun pentagonalp(n)
  (let ((p (/ (1+ (sqrt (1+ (* 24 n)) )) 6)))
    (> 0.0000000001 (- p (floor p)))))

(defun probl44()
;;  (declare (optimize (speed 3) (safety 0)))
  (let (( p (all-pentagonals 5000) ))
;;    (declare (type (simple-array fixnum (5000)) p))
    (loop ;with p = (all-pentagonals 5000)
       for i from 1 to (- (length p) 2)
       do (loop for j from (1+ i) to (1- (length p))
	     when (and (pentagonalp (- (elt p j) (elt p i)))
		       (pentagonalp (+ (elt p j) (elt p i))))
	     do (format t "(~d,~d)~d - ~d = ~d~%" j i (elt p j) (elt p i) (- (elt p j) (elt p i)))))))
 
 
 (defun pentagonal (n)
  (/ (* n (- (* 3 n) 1)) 2))

(defun list-pentagonals (max)
  (loop for i from 1 to max collect (pentagonal i)))

(defun find-pentagonals (max)
  (loop with p = (list-pentagonals max)
     for i in p
     do (loop for j in p 
	   when (and (/= i j) (find (+ i j) p) (find (- i j) p))
	   do (print (- i j)))))

(defun find-pentagonals (max)
  (loop with p = (list-pentagonals max)
     for xi from 0 to (1- (length p))
     for i = (nth xi p)
     do (loop for xj from (1+ xi) to (1- (length p))
	   for j = (nth xj p)
	   when (and (find (+ i j) p) (find (- j i) p))
	   do (format t "~d - ~d = ~d ~%"  j i (- j i)))))

(defun find-pentagonals (max)
  (loop with p = (list-pentagonals max)
     for i from 1 to max
     do (loop for a from 0 to (- (length p) i 1)
	   with i = (nth a p)
	   with j = (nth (+ a i) p)
	   when (and (find (+ i j) p) (find (- j i) p))
	   do (format t "~d - ~d = ~d ~%"  j i (- j i)))))

(defun array-pentagonals (max)
  (loop with v = (make-array max :fill-pointer 0)
     for i from 1 to max 
     do (vector-push (pentagonal i) v)
     finally (return v)))

(defun find-array-pentagonals (max)
  (loop with p = (array-pentagonals max)
     for dif from 1 to max
     do (loop for a from 0 to (- (length p) dif 1)
	   with i = (elt p a )
	   with j = (elt p (+ a dif))
	   when (and (find (+ i j) p)); (find (- j i) p))
	   do (format t "~d - ~d = ~d ~%"  j i (- j i)))))

(defun find-array-pentagonals (max)
  (loop with p = (array-pentagonals max)
     for i from 1 to (1- (length p))
     do (loop for j from (1+ i) to (1- (length p))
	     when (and (find (+ (elt p i) (elt p j)) p) (find (- (elt p j) (elt p i)) p))
	     do (format t "~d - ~d = ~d ~%"  (elt p j) (elt p i) (- (elt p j) (elt p i))))))